package tutorial.lite_mod.schedule_system;


import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.log4j.Logger;
import public_util.model.*;
import public_util.servlet.ServletParent;
import system_api_4_trade.dao.ApiPublicMiddleTableMapper;
import system_api_4_trade.util.sql.SelectTool;
import system_api_4_trade.util.tool_4_handle.DateToolApi;
import system_api_4_trade.util.tool_4_handle.StringToolApi;
import system_api_4_trade.util.tool_4_handle.Tool_4_ServletApi;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.*;

/**
 * 控制层用到的具体方法
 * 数据库索引需要修改
 ALTER TABLE `public_middle_table_lite_mod_schedule_system_sub_arrange`
 CHANGE `mid_table_remark_008` `mid_table_remark_008` VARCHAR (16) CHARSET utf8 COLLATE utf8_general_ci NULL,
 CHANGE `mid_table_remark_040` `mid_table_remark_040` VARCHAR (16) CHARSET utf8 COLLATE utf8_general_ci NULL,
 ADD UNIQUE INDEX `update_4_insert` (
 `id_public_user_info`,
 `mid_table_remark_008`,
 `mid_table_remark_040`
 ) ;

 */
class Tutorial4LiteModTool {

    private static Logger logger = Logger.getLogger(Tutorial4LiteModTool.class);

    /**
     * 生成排班的安排
     * 难点指定一下序列的问题
     * select * from public_user_info where id_public_user_info in (3923,3922) order by  FIELD(id_public_user_info,3923,3922)
     */
    public static ReturnData batch_generate_arrange_4_student(SqlSessionFactory sqlSession, ServletParent thisParent, HttpSession hsession, HttpServletResponse response, HttpServletRequest request){

        logger.info("----batch_generate_arrange_4_student----");
        ReturnData resultData = new ReturnData();
        PublicDataAdminUser adminUser = (PublicDataAdminUser) Tool_4_ServletApi.getAttribute(null, hsession, Const4PublicDataBase.MEM_4_self_public_data_admin_user);
        PublicAgentInfo agentInfo = (PublicAgentInfo)Tool_4_ServletApi.getAttribute(null, hsession,Const4PublicDataBase.MEM_4_self_public_agent_info);
        resultData = Tool_4_ServletApi.checkAccessType(hsession, resultData, 102);
        if (resultData.getStatus() != 0)
        {
            return resultData;
        }

        String id_admin = "-1";

        if (agentInfo != null)
        {
            id_admin = agentInfo.getId_public_data_admin_user() + "";
        }

        if (adminUser != null)
        {
            id_admin = adminUser.getId_public_data_admin_user() + "";
        }

        String id_public_middle_table = request.getParameter(Const4PublicDataBase.PARA_id_public_middle_table);
        id_public_middle_table = StringToolApi.paraHttpFilter(id_public_middle_table);
        if (id_public_middle_table == null)
        {
            resultData.setMsg("模板ID未传入");
            return resultData;
        }

        String id_public_user_info_list = request.getParameter("id_public_user_info_list");
        String time_4_begin = request.getParameter("time_4_begin");
        String time_4_end = request.getParameter("time_4_end");
        if (id_public_user_info_list == null)
        {
            resultData.setMsg("id_public_user_info_list-用户数据未传入");
            return resultData;
        }
        if (time_4_begin == null)
        {
            resultData.setMsg("time_4_begin-时间未传入");
            return resultData;
        }

        if (time_4_end == null)
        {
            resultData.setMsg("time_4_end-时间未传入");
            return resultData;
        }


        SqlSession session = sqlSession.openSession();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Transaction newTransaction = transactionFactory.newTransaction(session.getConnection(), false);
        ApiPublicMiddleTableMapper mMapper = session.getMapper(ApiPublicMiddleTableMapper.class);
        Tutorial4LiteModMapper liteModMapper = session.getMapper(Tutorial4LiteModMapper.class);
        try {

            //排班模板是否存在
            PublicMiddleTable mubanData = find_public_middle_table_muban(mMapper, id_public_middle_table);


            if (mubanData == null)
            {
                resultData.setMsg("排班模板信息不存在");
                return resultData;
            }

            String mid_table_remar_006 = mubanData.getMid_table_remark_006();
            if (mid_table_remar_006 == null)
            {
                resultData.setMsg("排班模板信息mid_table_remar_006不存在");
                return resultData;
            }
            String zhouqi_id[] = mid_table_remar_006.split(",");

            HashMap<String, Object> search006 = new HashMap<>();

            search006.put(Const4PublicDataBase.PARA_id_public_middle_table+ "_in", mid_table_remar_006);
            search006.put("pre_db_para_order_by_para", "FIELD(id_public_middle_table,"+ mid_table_remar_006 +")");
            search006.put("is_online", "0");
            HashMap<String, Object>  realPara = SelectTool.paramap2selectMap(search006, "public_middle_table_lite_mod_schedule_system");
            List<PublicMiddleTable> zhouqi = mMapper.tableDataList(realPara);// 周期的配置

            processBanci4Zhouqi(zhouqi, mMapper);

            if (zhouqi == null)
            {
                resultData.setMsg("班次的配置信息不存在");
                return resultData;
            }



            String[] id_userArr = id_public_user_info_list.split(",");
            List<PublicMiddleTable> list4Insert = new ArrayList<>();

            Date time_b = DateToolApi.parseDate("yyyy-MM-dd HH:mm:ss", time_4_begin + " 00:00:00");
            Date time_e = DateToolApi.parseDate("yyyy-MM-dd HH:mm:ss", time_4_end + " 00:00:00");
            if (time_b == null || time_e == null)
            {
                resultData.setMsg("时间参数有问题");
                return resultData;
            }
            for ( int i = 0; i < id_userArr.length; i++)
            {
                String id_user = id_userArr[i];
                int id_real = -1;
                try
                {
                    id_real = Integer.valueOf(id_user);
                }catch(Exception e)
                {
                    continue;
                }
                if (id_real > 0)
                {
                    findBathInsertArrangeMent4OneUser(time_b, time_e, mubanData, id_real, list4Insert, zhouqi, zhouqi_id);
                }
            }
            liteModMapper.bachInsert2table(list4Insert);
            session.commit();
            resultData.setStatus(0);
            return resultData;
        }
        catch(Exception e)
        {
            try {
                newTransaction.rollback();
                String msg = Tool_4_ServletApi.showStackTrace(e);
                resultData.setMsg(msg);
                return resultData;

            } catch (SQLException e1) {
                String msg = Tool_4_ServletApi.showStackTrace(e);
                resultData.setMsg(msg);
                return resultData;
            }
        }
        finally
        {
            session.close();
        }
    }


    /**
     *  修改排班数据
     */
    public static ReturnData modify_arrange_4_student(SqlSessionFactory sqlSession, ServletParent thisParent, HttpSession hsession, HttpServletResponse response, HttpServletRequest request){

        logger.info("----batch_generate_arrange_4_student----");
        ReturnData resultData = new ReturnData();
        PublicDataAdminUser adminUser = (PublicDataAdminUser) Tool_4_ServletApi.getAttribute(null, hsession, Const4PublicDataBase.MEM_4_self_public_data_admin_user);
        PublicAgentInfo agentInfo = (PublicAgentInfo)Tool_4_ServletApi.getAttribute(null, hsession,Const4PublicDataBase.MEM_4_self_public_agent_info);
        resultData = Tool_4_ServletApi.checkAccessType(hsession, resultData, 102);
        if (resultData.getStatus() != 0)
        {
            return resultData;
        }

        String id_admin = "-1";

        if (agentInfo != null)
        {
            id_admin = agentInfo.getId_public_data_admin_user() + "";
        }

        if (adminUser != null)
        {
            id_admin = adminUser.getId_public_data_admin_user() + "";
        }

        String id_public_middle_table = request.getParameter(Const4PublicDataBase.PARA_id_public_middle_table);
        id_public_middle_table = StringToolApi.paraHttpFilter(id_public_middle_table);
        if (id_public_middle_table == null)
        {
            resultData.setMsg("模板ID未传入");
            return resultData;
        }

        String id_public_user_info_list = request.getParameter("id_public_user_info_list");
        String time_4_begin = request.getParameter("time_4_begin");
        if (id_public_user_info_list == null)
        {
            resultData.setMsg("id_public_user_info_list-用户数据未传入");
            return resultData;
        }
        if (time_4_begin == null)
        {
            resultData.setMsg("time_4_begin-时间未传入");
            return resultData;
        }

        SqlSession session = sqlSession.openSession();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Transaction newTransaction = transactionFactory.newTransaction(session.getConnection(), false);
        ApiPublicMiddleTableMapper mMapper = session.getMapper(ApiPublicMiddleTableMapper.class);
        Tutorial4LiteModMapper liteModMapper = session.getMapper(Tutorial4LiteModMapper.class);
        try {

            HashMap<String, Object> search006 = new HashMap<>();
            search006.put(Const4PublicDataBase.PARA_id_public_middle_table+ "_in", id_public_middle_table);
            search006.put("pre_db_para_order_by_para", "FIELD(id_public_middle_table,"+ id_public_middle_table +")");
            search006.put("is_online", "0");
            search006.put("type_middle_app", "21001");
            search006.put("type_inner_app", "1001");
            HashMap<String, Object>  realPara = SelectTool.paramap2selectMap(search006, "public_middle_table_lite_mod_schedule_system");
            List<PublicMiddleTable> jichList = mMapper.tableDataList(realPara);// 周期的配置
            if (jichList == null || jichList.size() == 0)
            {
                resultData.setMsg("基础班单元不存在");
                return resultData;
            }



            String[] id_userArr = id_public_user_info_list.split(",");
            List<PublicMiddleTable> list4Insert = new ArrayList<>();

            Date time_b = DateToolApi.parseDate("yyyy-MM-dd HH:mm:ss", time_4_begin + " 00:00:00");
            if (time_b == null)
            {
                resultData.setMsg("时间参数有问题");
                return resultData;
            }
            for ( int i = 0; i < id_userArr.length; i++)
            {
                String id_user = id_userArr[i];
                int id_real = -1;
                try
                {
                    id_real = Integer.valueOf(id_user);
                }catch(Exception e)
                {
                    continue;
                }
                if (id_real > 0)
                {
                    findBathInsert4OneUserUpdate(time_b, id_real, list4Insert, jichList);
                }
            }
            liteModMapper.bachInsert2table(list4Insert);
            session.commit();
            resultData.setStatus(0);
            return resultData;
        }
        catch(Exception e)
        {
            try {
                newTransaction.rollback();
                String msg = Tool_4_ServletApi.showStackTrace(e);
                resultData.setMsg(msg);
                return resultData;

            } catch (SQLException e1) {
                String msg = Tool_4_ServletApi.showStackTrace(e);
                resultData.setMsg(msg);
                return resultData;
            }
        }
        finally
        {
            session.close();
        }
    }


    /**
     * 把周期的情况摸清楚
     * @param list4banci
     * @param id_mid
     * @return
     */
    private static PublicMiddleTable findTable4Frenqunce(List<PublicMiddleTable> list4banci, String id_mid)
    {
        if ("-1".equals(id_mid))
        {

            return null;
        }
        for (int i = 0; i < list4banci.size(); i++)
        {
            PublicMiddleTable itemTable = list4banci.get(i);
            if (id_mid.equals(itemTable.getId_public_middle_table() + ""))
            {
                return itemTable;
            }
        }
        return null;
    }


    private static void processBanci4Zhouqi(List<PublicMiddleTable> zhouqiList, ApiPublicMiddleTableMapper middleTableMapper)
    {
        for (int i = 0; i < zhouqiList.size(); i++)
        {
            PublicMiddleTable day_zuhe = zhouqiList.get(i);
            String mid_table_remar_006 = day_zuhe.getMid_table_remark_006();
            if (mid_table_remar_006 == null)
            {
                continue;
            }
            HashMap<String, Object> search006 = new HashMap<>();
            search006.put(Const4PublicDataBase.PARA_id_public_middle_table+ "_in", mid_table_remar_006);
            search006.put("pre_db_para_order_by_para", "FIELD(id_public_middle_table,"+ mid_table_remar_006 +")");
            search006.put("is_online", "0");
            HashMap<String, Object>  realPara = SelectTool.paramap2selectMap(search006, "public_middle_table_lite_mod_schedule_system");
            List<PublicMiddleTable> zhouqi = middleTableMapper.tableDataList(realPara);// 周期的配置
            day_zuhe.setSave_data_000(zhouqi);
        }
    }




    //排班模板是否存在
    public static PublicMiddleTable find_public_middle_table_muban(ApiPublicMiddleTableMapper midMapper, String id_mid)
    {
        HashMap<String, Object> paraPrice = new HashMap<String, Object>();
        paraPrice.put(Const4PublicDataBase.PARA_type_middle_app, 22001);
        paraPrice.put(Const4PublicDataBase.PARA_type_inner_app, 1001);
        paraPrice.put(Const4PublicDataBase.PARA_is_online, 0);
        paraPrice.put(Const4PublicDataBase.PARA_id_public_middle_table+ "_in", id_mid);
        HashMap<String, Object>  realPara = SelectTool.paramap2selectMap(paraPrice, "public_middle_table_lite_mod_schedule_system");
        List<PublicMiddleTable> listQianyuePrice = midMapper.tableDataList(realPara);//查询是否具备值
        if (listQianyuePrice == null || listQianyuePrice.size() == 0)
        {
            return null;
        }
        return listQianyuePrice.get(0);
    }

    private static void findBathInsertArrangeMent4OneUser(Date begin_day, Date end_day, PublicMiddleTable moduleData, int id_user, List<PublicMiddleTable> listMid, List<PublicMiddleTable> list4banci, String[] ban_id)
    {
        int add_second = 1;//0点不好判别是哪一天, 特增加1S
        Date process_day = begin_day;
        process_day = DateToolApi.addSecond(process_day, add_second);//增加一分一秒
        //按照时间来生成
        Calendar c=Calendar.getInstance();
        int frenqunce_len = ban_id.length;
        int currentIdx = 0;
        while(!process_day.after(DateToolApi.addSecond(end_day, add_second)))
        {
            //周末：1，  周一：2   ，周二3…… 周六：7
            int index = (currentIdx) % frenqunce_len;
            //跟下标对应起来
            String currentBanId = ban_id[index];//-1表示本天不作安排
            PublicMiddleTable zhouqi = findTable4Frenqunce(list4banci, currentBanId);
            if (zhouqi == null)
            {
                //下一条数据, 不用插入
                process_day = DateToolApi.addDays(process_day, 1);
                currentIdx++;
                continue;
            }
            List<PublicMiddleTable> listData = (List<PublicMiddleTable>)zhouqi.getSave_data_000();
            if (listData == null || listData.size() == 0)
            {
                //下一条数据, 不用插入
                process_day = DateToolApi.addDays(process_day, 1);
                currentIdx++;
                continue;
            }
            //当天的安排
            for (int i = 0; i < listData.size(); i++)
            {
                PublicMiddleTable dayItem = listData.get(i);
                PublicMiddleTable item = new PublicMiddleTable();
                item.setType_middle_app(23001);
                item.setType_inner_app(1001);
                item.setId_public_user_info(id_user);
                item.setIs_online("0");
                item.setMid_table_remark_001(dayItem.getMid_table_remark_001());
                item.setMid_table_remark_002(dayItem.getMid_table_remark_002());
                item.setMid_table_remark_003(dayItem.getMid_table_remark_003());
                item.setMid_table_remark_004(dayItem.getMid_table_remark_004());
                item.setMid_table_remark_008(dayItem.getId_public_middle_table() + "");
                item.setMid_table_remark_040(DateToolApi.format(process_day, "yyyyMMdd"));//年月日
                item.setMid_table_remark_041(DateToolApi.format(process_day, "yyyyMM"));//年月
                item.setMid_table_remark_042(DateToolApi.format(process_day, "yyyy"));//年
                item.setTime_insert(new Date());
                item.setTime_update(new Date());
                item.setTime_4_begin(process_day);
                item.setId_public_data_admin_user(800);
                listMid.add(item);
            }

            //下一条数据
            process_day = DateToolApi.addDays(process_day, 1);
            currentIdx++;
        }
    }


    private static void findBathInsert4OneUserUpdate(Date begin_day, int id_user, List<PublicMiddleTable> listMid,List<PublicMiddleTable> listData)
    {
        int add_second = 1;//0点不好判别是哪一天, 特增加1S
        Date process_day = begin_day;
        process_day = DateToolApi.addSecond(process_day, add_second);//增加一分一秒
        //按照时间来生成
        //当天的安排
        for (int i = 0; i < listData.size(); i++)
        {
            PublicMiddleTable dayItem = listData.get(i);
            PublicMiddleTable item = new PublicMiddleTable();
            item.setType_middle_app(23001);
            item.setType_inner_app(1001);
            item.setId_public_user_info(id_user);
            item.setIs_online("0");
            item.setMid_table_remark_001(dayItem.getMid_table_remark_001());
            item.setMid_table_remark_002(dayItem.getMid_table_remark_002());
            item.setMid_table_remark_003(dayItem.getMid_table_remark_003());
            item.setMid_table_remark_004(dayItem.getMid_table_remark_004());
            item.setMid_table_remark_008(dayItem.getId_public_middle_table() + "");
            item.setMid_table_remark_040(DateToolApi.format(process_day, "yyyyMMdd"));//年月日
            item.setMid_table_remark_041(DateToolApi.format(process_day, "yyyyMM"));//年月
            item.setMid_table_remark_042(DateToolApi.format(process_day, "yyyy"));//年
            item.setTime_insert(new Date());
            item.setTime_update(new Date());
            item.setTime_4_begin(process_day);
            item.setId_public_data_admin_user(800);
            listMid.add(item);
        }
    }




}